package com.example.webview.webviewprocess;

import android.content.Context;
import android.os.Process;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Toast;

import com.example.webview.WebViewCallback;
import com.example.webview.bean.JsCommand;
import com.example.webview.webviewprocess.dispatcher.WebViewCommandDispatcher;
import com.example.webview.webviewprocess.settings.WebViewSettingsUtil;
import com.example.webview.webviewprocess.webchromeclient.CustomWebChromeClient;
import com.example.webview.webviewprocess.webviewclient.CustomWebViewClient;
import com.google.gson.Gson;

/**
 * Created by ymz0427 on 2021/9/30
 */
public class CustomWebView extends WebView {

    private static final String TAG = "CustomWebView";


    public CustomWebView(Context context) {
        super(context);
        init();
    }

    public CustomWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public CustomWebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    private void init() {
        WebViewCommandDispatcher.getInstance().initProcessService();
        WebViewSettingsUtil.setSettings(this);
        addJavascriptInterface(this, "jsObject");
    }

    @JavascriptInterface
    public void takeNativeAction(String jsParam) {
        System.out.println("触发进程id：" + Process.myPid() + ", 命令：" + jsParam);
        if (!TextUtils.isEmpty(jsParam)) {
            Gson gson = new Gson();
            JsCommand command = gson.fromJson(jsParam, JsCommand.class);
            if (!TextUtils.isEmpty(command.getName()) && command.getParam() != null) {
                WebViewCommandDispatcher.getInstance().executeCommand(command.getName(), gson.toJson(command.getParam()), this);
            }
        }
    }

    public void registerCallback(WebViewCallback callback) {
        setWebChromeClient(new CustomWebChromeClient(callback));
        setWebViewClient(new CustomWebViewClient(callback));
    }

    public void handleCallback(String callbackname, String response) {
        post(new Runnable() {
            @Override
            public void run() {
                String javascript = "javascript:myjs.callback('" + callbackname + "'," + response + ")";
                evaluateJavascript(javascript, null);
            }
        });
    }

}
